
// 导入request请求工具类
import {getBaseUrl,requestUtil} from '../../utils/requestUtil';
import regeneratorRuntime from '../../lib/runtime/runtime';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    address:{},
    baseUrl:'',
    cart:[],
    allChecked:false,
    totalPrice:0,
    totalNum:0

  },

handleChooseAddress(){
wx.chooseAddress({
  success: (result)=>{
    console.log(result)
    wx.setStorageSync('address', result)
  },
})
},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad:function (options) {
    const baseUrl =getBaseUrl();
    this.setData({
    baseUrl
   })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady:function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow:function() {
    console.log("show")
    const address=wx.getStorageSync('address');
    const cart=wx.getStorageSync('cart')||[];
  

    this.setData({
      address
    })
    this.setCart(cart);

  },

  // 商品选中事件处理
  handeleItemChange(e){
    const{id}=e.currentTarget.dataset;
    let {cart}=this.data;
    let index=cart.findIndex(v=>v.id===id);
    cart[index].checked=!cart[index].checked;

    this.setCart(cart);
  },
//商品全选事件处理
handeleItemAllCheck(){
  let{cart,allChecked}=this.data;
console.log(cart,allChecked)
allChecked=!allChecked;
cart.forEach(v=>v.checked=allChecked);
this.setCart(cart);
},

//商品数量加减
handeleItemNumEdit(e){
  const{id,operation}=e.currentTarget.dataset;
  console.log(id,operation)
  let {cart}=this.data;
  let index=cart.findIndex(v=>v.id===id);

  if(cart[index].num === 1 && operation=== -1 ){
  wx.showModal({
    title: '系统提示',
    content: '您是否要删除？',
    cancelColor:'cancelColor',
    success: (res) => {
      if (res.confirm) {
        cart.splice(index,1);
        this.setCart(cart);

      }
    }
  })
  }else{
  cart[index].num+=operation;
  this.setCart(cart);
  }


},
//点击结算
handlePay(){
 const {address,totalNum}=this.data;
 if(!address){
   wx.showToast({
     title: '您还没有选择收货地址',
     icon:'none'
   })
   return;
 }
 if(totalNum===0){
  wx.showToast({
    title: '您还没有选购商品',
    icon:'none'
  })
  return;
}
wx.navigateTo({
  url: '/pages/pay/index',
})
},


  // 设置购物车状态，重新计算底部工具栏的全选、总价、总数，重新设置缓存
  setCart(cart){
    let allChecked=true;
    let totalPrice=0;
    let totalNum=0;
    cart.forEach(v=>{
      if(v.checked){
                totalNum+=v.num;
                totalPrice+=v.price*v.num;
      }
      else{
        allChecked=false;
      }
    })
    allChecked=cart.length!=0?allChecked:false;

    this.setData({
      cart,
      allChecked,
      totalNum,
      totalPrice
    })
// cart设置到缓存中
 wx.setStorageSync('cart', cart);

  }
})